import 'dart:async';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wan_android/pages/page_web.dart';

///封装列表item 三个item 都可用状态
class ItemWidget extends StatefulWidget {
  final String firApi; //第一段api
  final String secApi; //第二段api
  final bool isFavorite; //true  收藏里面的数据  就不显示 种类
  final bool isSearch; // true  搜索的数据  不显示种类
  final String searchStr; // 只有搜素的时候 会传入

  ItemWidget(
      {this.firApi,
      this.secApi,
      this.isFavorite,
      this.isSearch,
      this.searchStr});

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return ItemWidgetState();
  }
}

class ItemWidgetState extends State<ItemWidget> {
  int page = 0;
  ScrollController scrollController = new ScrollController(); //滑动控制器
  List<ItemEntity> itemList = []; //数据

  bool isLoading = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _initData();
    scrollController.addListener(() {
      if (scrollController.position.maxScrollExtent ==
          scrollController.position.pixels) {
        _initData();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return RefreshIndicator(
      child: ListView.builder(
        itemBuilder: (BuildContext context, int index) {
          return _getWidget(itemList[index]);
        },
        itemCount: itemList.length,
        controller: scrollController,
      ),
      onRefresh: _handleRefreshMethod,
      color: Colors.red,
    );
  }

  ///初始化数据
  _initData() async {
    if (isLoading) {
      print('正在加载中');
      return;
    }
    isLoading = true;
    Dio dio = new Dio();
    String api = '${widget.firApi}$page${widget.secApi}';
    print('api: $api');
    if (widget.isSearch) {
      //搜索界面
      FormData formData = FormData.from({'k': widget.searchStr});
      await dio.post(api, data: formData).then((value) {
        print(value);
        var values1 = value.data['data']['datas'];
        for (var listdata in values1) {
          ItemEntity entity = ItemEntity.fromJson(listdata);
          itemList.add(entity);
        }
        setState(() {
          page++;
        });
      }).catchError((error) {
        print(error);
      }).whenComplete(() {
        isLoading = false;
      });
    } else {
      if (widget.isFavorite) {
        //收藏界面
        SharedPreferences sp = await SharedPreferences.getInstance();
        Map<String, String> map = new Map();
        map['Cookie'] = sp.get('cookie');
        dio.options = Options(
          baseUrl: api,
          headers: map,
        );
      }
      await dio.get(api).then((value) {
        print('item ui');
        print(value.data);
        var listData = value.data['data']['datas'];
        print(listData);
        for (var data in listData) {
          print(data);
          ItemEntity entity = ItemEntity.fromJson(data);
          itemList.add(entity);
        }
        setState(() {
          page++;
        });
      }).catchError((error) {
        print('item ui error');
        print(error);
      }).whenComplete(() {
        isLoading = false;
      });
    }
  }

  ///刷新事件  就是重新请求
  ///这个必须返回一个 Future<NULL>
  Future<Null> _handleRefreshMethod() async {
    print('item 执行刷新');
    if (itemList.length > 0) {
      setState(() {
        page = 0;
        itemList.clear();
      });
      _initData();
    }
  }

//  //下拉刷新
//  Future<Null> _handleRefresh() async {
//    await Future.delayed(Duration(seconds: 5), () {
//      print('refresh');
//      setState(() {
//        items.clear();
//        items = List.generate(40, (i) => i);
//        return null;
//      });
//    });
//  }

  //http://www.wanandroid.com/lg/collect/1165/json post
  String collectionApi = 'http://www.wanandroid.com/lg/collect/';

  ///http://www.wanandroid.com/lg/uncollect_originId/
  String unCollectionApi = 'http://www.wanandroid.com/lg/uncollect_originId/';

  ///收藏和取消收藏
  _collectionArti(int id, ItemEntity entity) async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    Map<String, String> map = new Map();
    map['Cookie'] = sp.getString('cookie');
    String url;
    if (widget.isFavorite) {
      url = unCollectionApi + '$id/json';
    } else {
      if (entity.collect) {
        url = unCollectionApi + '$id/json';
      } else {
        url = collectionApi + '$id/json';
      }
    }

    Dio dio = Dio(Options(baseUrl: url, headers: map));
    await dio.post(url).then((value) {
      if (value.statusCode == 200) {
        setState(() {
          if (widget.isFavorite) {
            itemList.remove(entity);
          } else {
            entity.collect = !entity.collect;
          }
        });
      } else {
        print('收藏失败');
      }
    }).catchError((error) {
      print(error);
    });
    print('收藏完毕');
  }

  ///文章列表ui
  Widget _getWidget(ItemEntity itemEntity) {
    if (itemEntity == null) {
      return Center(
        child: Text('清稍等'),
      );
    }
    String showTitle;
    if (widget.isSearch) {
      String replaceStr = "<em class='highlight'>${widget.searchStr}</em>";
      showTitle =
          itemEntity.artTitle.replaceAll(RegExp(replaceStr), widget.searchStr);
    } else {
      showTitle = itemEntity.artTitle;
    }

    print('ui 列表: ${widget.isSearch}..$showTitle');

    return Container(
      child: GestureDetector(
        child: Card(
          child: Padding(
            padding:
                EdgeInsets.only(left: 10.0, right: 10.0, top: 5.0, bottom: 5.0),
            child: Column(
              children: <Widget>[
                Expanded(
                  flex: 1,
                  child: Row(
                    children: <Widget>[
                      Expanded(
                        child: Text.rich(
                          TextSpan(
                          text: '作者: ',
                          style: TextStyle(fontSize: 14.0),
                          children: <TextSpan>[
                            TextSpan(
                              text: itemEntity.name,
                              style: TextStyle(
                                  color: Colors.blueAccent, fontSize: 15.0),
                            ),
                          ],
                        ),
                        ),
                      ),
                      Text(itemEntity.dateTime),
                    ],
                  ),
                ),
                Expanded(
                  flex: 2,
                  child: Align(
                    alignment: AlignmentDirectional.centerStart,
                    child: Text(
                      showTitle,
                      style: TextStyle(fontSize: 16.0,),
                      textAlign: TextAlign.left,
                      softWrap: true,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ),
                Expanded(
                  child: Row(
                    children: <Widget>[
                      Expanded(
                        child: Text((widget.isFavorite || widget.isSearch)
                            ? ""
                            : itemEntity.type,
                        style: TextStyle(fontSize: 14.0),
                        ),
                      ),
                      IconButton(
                        icon: Icon(
                          Icons.favorite,
                          color: widget.isFavorite
                              ? Colors.red
                              : (itemEntity.collect ? Colors.red : Colors.grey),
                        ),
                        onPressed: () {
                          _collectionArti(itemEntity.id, itemEntity);
                        },
                      ),
                    ],
                  ),
                  flex: 1,
                ),
              ],
            ),
          ),
          elevation: 5.0,
          margin:
              EdgeInsets.only(left: 10.0, top: 5.0, right: 10.0, bottom: 15.0),
        ),
        onTap: () {
          print('执行了跳转点击');
          Navigator.of(context).push(
            MaterialPageRoute(
              builder: (context) {
                return PageWeb(
                  title: showTitle,
                  webUrl: itemEntity.link,
                );
              },
            ),
          );
        },
      ),
      height: 140.0,
    );
  }
}

class ItemEntity {
  int id; //文章id
  String name; //作者名字
  String artTitle; //文章标题
  String type; //文章类型
  String dateTime; //发表时间点
  bool collect; //图标     //收藏界面没有collect 这个界面
  String link; //文章链接

  ItemEntity({
    this.id,
    this.name,
    this.artTitle,
    this.type,
    this.dateTime,
    this.collect,
    this.link,
  });

  factory ItemEntity.fromJson(Map<String, dynamic> map) {
    return ItemEntity(
      id: map['id'],
      name: map['author'],
      artTitle: map['title'],
      type: map['superChapterName'],
      dateTime: map['niceDate'],
      collect: map['collect'],
      link: map['link'],
    );
  }
}
